package com.canplay.screen.network

import android.annotation.SuppressLint
import com.canplay.screen.BuildConfig
import com.google.gson.Gson
import okhttp3.OkHttpClient
import retrofit2.Retrofit
import retrofit2.adapter.rxjava3.RxJava3CallAdapterFactory
import retrofit2.converter.gson.GsonConverterFactory
import java.net.Proxy
import java.security.SecureRandom
import java.security.cert.X509Certificate
import javax.net.ssl.*

object RetrofitManager {
    private const val BASE_URL = BuildConfig.APIHOST

    fun getOkHttpClient(): OkHttpClient {

        val trustAllCerts = arrayOf<TrustManager>(
            @SuppressLint("CustomX509TrustManager")
            object : X509TrustManager {
                @SuppressLint("TrustAllX509TrustManager")
                override fun checkClientTrusted(chain: Array<X509Certificate>, authType: String) {
                }

                @SuppressLint("TrustAllX509TrustManager")
                override fun checkServerTrusted(chain: Array<X509Certificate>, authType: String) {
                }

                override fun getAcceptedIssuers(): Array<X509Certificate> {
                    return arrayOf()
                }
            }
        )
        val sslContext = SSLContext.getInstance("SSL")
        sslContext.init(null, trustAllCerts, SecureRandom())
        val sslSocketFactory = sslContext.socketFactory

        val maxRequestSize: Long = 10 * 1024 * 1024  // 设置最大请求体大小为 10MB
        return OkHttpClient
            .Builder()
            .proxy(if (BuildConfig.DEBUG) null else Proxy.NO_PROXY)
            .sslSocketFactory(sslSocketFactory, (trustAllCerts[0] as X509TrustManager))
            .hostnameVerifier { _, _ -> true }
            .addInterceptor(HeaderInterceptor())
            .addInterceptor(MaxRequestSizeInterceptor(maxRequestSize))
            .addNetworkInterceptor(Code405Interceptor())
            .build()
    }

    private fun getRetrofit(): Retrofit {
        return Retrofit
            .Builder()
            .baseUrl(BASE_URL)
            .addConverterFactory(GsonConverterFactory.create())
            .addCallAdapterFactory(RxJava3CallAdapterFactory.create())
            .client(getOkHttpClient())
            .build()
    }

    private fun getCustomGson(): Gson {
        val gsonBuilder = Gson().newBuilder()
        gsonBuilder.registerTypeAdapter(List::class.java, ArraySecurityAdapter())
        gsonBuilder.registerTypeAdapterFactory(GsonTypeAdapterFactory())
        return gsonBuilder.create()
    }

    fun <T> createApi(service: Class<T>): T {
        return getRetrofit().create(service)
    }
}